//
//  BWUserAccountModel.swift
//  weibo
//
//  Created by libowen on 16/5/23.
//  Copyright © 2016年 libowen. All rights reserved.
//

import UIKit
private let userInfoKey = "com.itheima.userInfoKey"
class BWUserAccountModel: NSObject {
    static let sharedAccountViewModel: BWUserAccountModel = BWUserAccountModel()
    var userAccount: BWUserAccount?
    
    private override init() {
        super.init()
        userAccount = loadUserAccount()
    }
    var userLogin: Bool {
        if userAccount?.expires_date?.compare(NSDate()) == .OrderedDescending {
            return true
        }
        userAccount = nil
        return false
    }
    var headURL: NSURL? {
        get {
            return NSURL(string: userAccount?.avatar_large ?? "")
        }
    }
}

extension BWUserAccountModel {
     func loadAccessToken(code: String, finished: (isSuccess: Bool) -> ()) {
        BWNetworkTool.sharedTools.loadAccessToken(code) { (responseObject, error) -> () in
            if error != nil {
                finished(isSuccess: false)
                return
            }
            self.loadUserInfo(responseObject, finished: finished)
        }
    }
    
    private func loadUserInfo(response: AnyObject?, finished: (isSuccess: Bool) -> ()) {
        guard let result = response as? [String : AnyObject] else {
            return
        }
        
        BWNetworkTool.sharedTools.loadUserInfo(result) { (responseObject, error) -> () in
            
            if error != nil {
                finished(isSuccess: false)
                return
            }
            guard var dict = responseObject as? [String : AnyObject] else {
                finished(isSuccess: false)
                return
            }
            for (key, value) in result {
                dict[key] = value
            }
            self.saveUserAccount(dict)
            finished(isSuccess: true)
//            print(dict)
        }
    }
    
}

extension BWUserAccountModel {
    func saveUserAccount(dict: [String : AnyObject]) {
        let user = BWUserAccount(dict: dict)
        self.userAccount = user
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        let userInfo = user.dictionaryWithValuesForKeys(keys)
        print(userInfo)
        let userDefaults = NSUserDefaults.standardUserDefaults()
        userDefaults.setObject(userInfo, forKey: userInfoKey)
        userDefaults.synchronize()
        print(NSHomeDirectory())
    }
    
    func loadUserAccount() -> BWUserAccount? {
        guard let dict = NSUserDefaults
            .standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else {
                return nil
        }
        let user = BWUserAccount(dict: dict)
        return user
    }
}

























